const moment = require('moment');
const { Controller } = require('../lib/contorller');
const {checkerModel } = require('../lib/mongo');

module.exports = class CheckerController extends Controller {
  async updateChecker() {
    const {
      ctx,
    } = this;
    const {
      id,
      validateIdList,
      describe,
      name,
    } = ctx.request.body;
    if(!describe || !name){
      ctx.result.message = '缺少参数';
      return;
    }
    let info = await checkerModel.findById(id);
    ctx.result.message = `${!info ? '新增' : '更新'} Checker`;
    const checkerObj = {
      validateIdList: validateIdList,
      describe,
      name,
      updateTime: moment().format('yyyy-MM-DD hh:mm:ss'),
    };
    if(!info){
      info = await checkerModel.create(checkerObj);
    }
    info = Object.assign(info,checkerObj);
    const checker = await info.save();

    if (checker.errors) {
      ctx.result.success = false;
    } else {
      ctx.result.success = true;
      ctx.result.info = checker;
    }
  }

  async deleteCheckerById() {
    const {
      ctx,
    } = this;
    const {
      id,
    } = ctx.request.query;
    if(!id){
      ctx.result.message = '缺少参数';
      return;
    }
    const info = await checkerModel.findByIdAndDelete(id);
    if (info.errors) {
      ctx.result.success = false;
      ctx.result.message = info.errors;
      return;
    }
    ctx.result.success = true;
    ctx.result.message = '删除checker';
  }

  async getAllChecker() {
    const {
      ctx,
    } = this;
    const info = await checkerModel.find({}).lean();
    ctx.result.message = '查询所有checker';
    if (info) {
      ctx.result.success = true;
    }
    ctx.result.info = info.map(item => {
      item.id = item._id;
      delete item._id;
      return item;
    });
  }

  async getChecker() {
    const {
      ctx,
    } = this;
    const {
      id,
    } = ctx.request.query;
    if(!id){
      ctx.result.message = '参数不正确';
      return;
    }
    const info = await checkerModel.findById(id).lean();
    const returnObj = {
      id: info._id,
      name: info.name,
      describe: info.describe,
      validateIdList: info.validateIdList,
    };
    if (info) {
      ctx.result.success = true;
      ctx.result.info = returnObj;
      ctx.result.message = '根据id查询checker成功';
    }
  }
};